# coding:utf-8
# @Time : 2021/5/10 16:49 
# @Author : minuy
# @File : okami.py
import random
from datetime import date
from random import randrange

from flask import request

from app import login_auth, db
from app.api import api
from app.api.interface import api_result
from app.libs.constellation_tool import zodiac
from app.libs.verification_tool import is_http_url, is_number
from app.models.okami import Okami
from app.models.profile import Profile
from app.models.user import User


@api.route('/okami/details')
def okami_details():
    # user在关注这部分用
    user = login_auth.current_user
    # 兼容提交
    json_data = request.get_json()
    args_data = request.args
    if json_data:
        post_form = json_data
    else:
        post_form = args_data
    print(post_form)

    if post_form:
        okami_id = post_form.get('id')
        try:
            okami_id = int(okami_id)
        except ValueError as e:
            print('格式错误', e)
            return api_result(code=403, message='格式错误')

        okami_info = Okami.query.filter_by(id=okami_id).first()
        user_info = None
        user_profile = None
        if okami_info:
            print('发布信息', okami_info)
            user_info = User.query.filter_by(id=okami_info.user_id).first()
            if user_info:
                print('用户信息', user_info)
                user_profile = Profile.query.filter_by(user_id=user_info.id).first()

        if user_profile:
            print('用户资料', user_profile)
            birthday = user_profile.birthday
            print(birthday, date.today())

            if not birthday:
                birthday = date.today()

            age = (date.today() - birthday).days // 365

            if user_info.sex == '男':
                sex_age = '♂' + str(age)
            else:
                sex_age = '♀' + str(age)

            okami_info.views = okami_info.views + 1

            feature_list = []

            if okami_info.ch_mik:
                feature_list.append('开麦')
            if okami_info.ch_fly:
                feature_list.append('带飞')
            if okami_info.ch_nth:
                feature_list.append('声音好听')
            if okami_info.ch_rap:
                feature_list.append('急速接单')

            img_list = []

            if user_profile.avatar:
                img_list.append({
                    'src': user_profile.avatar
                })
            if user_profile.photo1:
                img_list.append({
                    'src': user_profile.photo1
                })
            if user_profile.photo2:
                img_list.append({
                    'src': user_profile.photo2
                })
            if user_profile.photo3:
                img_list.append({
                    'src': user_profile.photo3
                })
            if user_profile.photo4:
                img_list.append({
                    'src': user_profile.photo4
                })

            detailed = {
                'user': {
                    'id': user_info.id,
                    'avatar': user_profile.avatar,
                    'name': user_info.nickname,
                    'sexAge': sex_age,  # 性别年龄
                    'type': "error" if user_info.sex == '女' else 'primary',
                    'views': okami_info.views,  # 浏览量
                    'orderVolume': okami_info.order_volume,  # 订单量
                    'score': okami_info.score,
                    'birthday': '{}'.format(birthday),
                    'constellation': zodiac(md=birthday),
                    'region': user_profile.region,
                    'signature': user_profile.signature,
                    # TODO 调取自己的关注列表，查看是否已关注
                    'isFollow': False if random.randint(0, 9) > 4 else True
                },
                'okami': {
                    'price': okami_info.price,
                    'isServer': True if okami_info.type == '服务' else False,
                    'describe': okami_info.describe,
                    'gameName': okami_info.game,
                    # TODO 段位
                    'gameRank': "",
                    'requirement': feature_list,
                    'imgList': img_list
                }
            }

            try:
                db.session.commit()
            except Exception as e:
                print('添加访问记录失败', e)

            return api_result(data={
                'detailed': detailed
            })
        else:
            return api_result(code=403, message='用户资料不完整')
    return api_result(code=403, message='提交参数不完整')


@api.route('/index')
def index_hall():
    okami_list = []
    read_list = []
    count_okami = db.session.query(Okami).count()
    print('数据库长度', count_okami)
    count_query = count_okami
    if count_okami > 10:
        count_query = 10
    print('查询长度', count_query)

    while len(read_list) < count_query:
        rand = randrange(0, count_okami)
        print('取出的随机数', rand)
        if rand not in read_list:
            read_list.append(rand)
    print('所有随机数', read_list)

    for i in read_list:
        row = db.session.query(Okami)[i]
        if row:
            user_info = User.query.filter_by(id=row.user_id).first()
            user_profile = Profile.query.filter_by(user_id=user_info.id).first()
            birthday = user_profile.birthday
            print(birthday, date.today())
            if not birthday:
                birthday = date.today()

            age = (date.today() - birthday).days // 365

            feature_list = []

            if row.ch_mik:
                feature_list.append('开麦')
            if row.ch_fly:
                feature_list.append('带飞')
            if row.ch_nth:
                feature_list.append('声音好听')
            if row.ch_rap:
                feature_list.append('急速接单')

            rank = ''
            trait = ''

            if feature_list:
                rank = feature_list[0]

            if len(feature_list) > 1:
                trait = feature_list[1]

            service = False

            if row.type == '服务':
                service = True

            price = '免费'
            if row.price:
                price = '{:.2f}币'.format(float(row.price))

            res = {
                'id': row.id,
                'username': user_info.nickname,
                'sex': user_info.sex,
                'age': age,
                'avatar': user_profile.avatar,
                'game': row.game,
                'rank': rank,
                'trait': trait,
                'price': price,
                'unit': row.unit,
                'descriptor': row.describe,
                'service': service
            }
            okami_list.append(res)
    return api_result(data={
        'okami_list': okami_list
    })


@api.route('/okami/publish', methods=['POST'])
@login_auth.login_required
def okami_publish():
    """
    发布需求、服务
    :return: 发布结果，成功、失败
    """
    user_register_info = request.get_json()
    user = login_auth.current_user
    print(user_register_info)
    if user_register_info and user:
        photo = user_register_info.get('photo')  # 图片
        o_type = user_register_info.get('type')  # 类别
        describe = user_register_info.get('describe')  # 描述
        unit = user_register_info.get('unit')  # 价格
        game = user_register_info.get('game')  # 游戏名
        characteristic = user_register_info.get('characteristic')  # 特点
        price = user_register_info.get('price')  # 价格

        ch_mik = 0  # 开麦？
        ch_fly = 0  # 带飞？
        ch_nth = 0  # 好听？
        ch_rap = 0  # 急速？

        if photo and \
                o_type and \
                describe and \
                unit and \
                game and \
                characteristic and \
                price:
            if not (is_number(price)):
                print('价格不正确', price)
                return api_result(code=403, message='价格不正确')
            if not is_http_url(photo):
                print('图片地址不正确', photo)
                return api_result(code=403, message='图片地址不正确')
            if not (o_type == '服务' or o_type == '需求'):
                print('类型不正确', o_type)
                return api_result(code=403, message='类型不正确')
            if not (0 <= len(describe) <= 200):
                print('描述不符合要求', describe)
                return api_result(code=403, message='描述不符合要求')
            if not (unit == '一局' or unit == '半小时' or unit == '一天'):
                print('单位不符合要求', unit)
                return api_result(code=403, message='单位不符合要求')
            if not (game == '第五人格' or game == '王者荣耀' or game == '和平精英'):
                print('游戏不符合要求', game)
                return api_result(code=403, message='游戏不符合要求')
            if characteristic:
                if '能开麦' in characteristic:
                    ch_mik = 1  # 开麦？
                if '带飞' in characteristic:
                    ch_fly = 1  # 带飞？
                if '声音好听' in characteristic:
                    ch_nth = 1  # 好听？
                if '急速接单' in characteristic:
                    ch_rap = 1  # 急速？

            # 完成数据校验
            try:
                print('完成数据校验')
                okami_info = Okami(user_id=user.id,
                                   photo=photo,
                                   type=o_type,
                                   describe=describe,
                                   unit=unit,
                                   price=price,
                                   game=game,
                                   ch_mik=ch_mik,  # 开麦？
                                   ch_fly=ch_fly,  # 带飞？
                                   ch_nth=ch_nth,  # 好听？
                                   ch_rap=ch_rap)  # 急速？
                db.session.add(okami_info)
                db.session.commit()
            except Exception as e:
                print('写入数据时出错', e)
                return api_result(code=500, message='写入数据时出错')

            return api_result(code=200, message='发布成功')
    return api_result(code=403, message='参数不完整')
